import { Sprite } from 'cc';
import { UITransform } from 'cc';
import { v2 } from 'cc';
import { sys } from 'cc';
import { ResolutionPolicy } from 'cc';
import { Size } from 'cc';
import { view } from 'cc';
import { SpriteFrame } from 'cc';
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass
export default class LayoutEx {

        /**
     * 等比缩放节点到屏幕大小 无黑边 可截断 返回值：最终放大比例
     * @param node 待缩放的节点
     */
    public static scaling(node: Node, spriteFrame?: SpriteFrame): number {
        spriteFrame = spriteFrame || node.getComponent(Sprite).spriteFrame;
        if (!spriteFrame) return 0;
        let root = view.getVisibleSize();
        let texture = spriteFrame.texture;
        let r_texture = texture.width / texture.height;
        let r_root = root.width / root.height;
        if (r_texture < r_root) {
            node.getComponent(UITransform).width = root.width;
            node.getComponent(UITransform).height = root.width / r_texture;
        } else {
            node.getComponent(UITransform).height = root.height;
            node.getComponent(UITransform).width = root.height * r_texture;
        }
        return node.getComponent(UITransform).width / texture.width
    }

    /** 指定尺寸，根据屏幕大小，获得等比缩放因子 */
    public static getScaleForSize(size: Size) :number {
        let root = view.getVisibleSize();
        let r_root = root.width / root.height;
        let r_size = size.width / size.height;
        if (r_root < r_size) {
            return root.height / size.height;
        } else {
            return root.width / size.width;
        }
    }

    /** 根据配置中的设计尺寸来计算，当前屏幕的上下, 左右偏移量 */
    public static getOffsetHeight() {
        let size = new Size(750, 1334);
        let type = view.getResolutionPolicy();
        // if (type != ResolutionPolicy.FIXED_WIDTH) return;
        let root = view.getVisibleSize();
        let scale = root.width / size.width;
        let top = this.getSafeAreaSpace();
        return (root.height - size.height * scale) * 0.5 - top;
    }

    /** 获取上下的safeaear高度 */
    public static getSafeAreaSpace() {
        let root = view.getVisibleSize();
        let rect = sys.getSafeAreaRect();
        let top = Math.max(rect.y, root.height - rect.height - rect.y);
        return top;
    }

    public static getDesignScale() {
        let size = new Size(750, 1334);
        let root = view.getVisibleSize();
        let scale = root.width / size.width;
        return scale;
    }

    /** 获取设计尺寸的长宽比 */
    public static getDesignLenWiRatio() {
        return 1334 / 750;
    }

    public static getViewLenWiRatio() {
        let root = view.getVisibleSize();
        return root.height / root.width;
    }

    /** 更新节点的y坐标， */
    public static updateY(node:Node, offset:number) {
        let pt = node.getPosition();
        pt.y += offset;
        node.setPosition(pt);
    }

}